/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.util;

import ohos.utils.zson.ZSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * 处理json字符串
 *
 * @since 2021-04-16
 */
public class JsonUtil {
    /**
     * Don't let anyone instantiate this class.
     */
    private JsonUtil() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }


    /**
     * 把 JSON 字符串 转换为 单个指定类型的对象
     *
     * @param json 包含了单个对象数据的JSON字符串
     * @param classOfT 指定类型对象的Class
     * @return 指定类型对象
     */
    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return new Gson().fromJson(json, classOfT);
        } catch (JsonParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析Json字符串
     *
     * @param json Json字符串
     * @param typeOfT 泛型类
     * @param <T>
     * @return 泛型类对象
     */
    public static <T> T fromJson(String json, Type typeOfT) {
        try {
            return new Gson().fromJson(json, typeOfT);
        } catch (JsonParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把 单个指定类型的对象 转换为 JSON 字符串
     *
     * @param src
     * @return json字符串
     */
    public static String toJson(Object src) {
        return new Gson().toJson(src);
    }

    /**
     * 把 单个指定类型的对象 转换为 JSONObject对象
     *
     * @param src
     * @return ZSONObject对象
     */
    public static ZSONObject toJSONObject(Object src) {
        return toJSONObject(toJson(src));
    }

    /**
     * 把 JSON 字符串 转换为 JSONObject对象
     *
     * @param json
     * @return ZSONObject对象
     */
    public static ZSONObject toJSONObject(String json) {
        ZSONObject jsonObject = null;
        try {
            jsonObject = ZSONObject.stringToZSON(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
